import { openAppClient, showLoading, hideLoading, webprintReport } from '@/utils/common'
import fn  from '@/utils/checkEmpty.js'
import auditRequest from '@/api/turnover/audit.js'
async function exas (arg, vueObject, requestFn, printData) {
    const _this = vueObject
    if (arg === 'audit') {
        showLoading()
        _this.errorList = []
        Promise.all(requestFn())
            .then(() => {
                hideLoading()
                _this.setAuditParams(_this.auditParams)
                // 客户端弹窗弹出本地页面
                openAppClient('/exaDialog', '填写审核意见', () => {
                    const auditParams = JSON.parse(localStorage.vuex).auditParams
                    showLoading()
                    auditRequest.audit(auditParams).then(() => {
                        hideLoading()
                        _this.clientPop('suc', '审核成功', _this.handleClose)
                    }).catch(()=>{
                        hideLoading()
                    })
                }, null, null, null, 'small')

            })
            .catch(err => {
                console.log('errMsg：', err)
                _this.scorllError()
            })
            .finally(() => {
                hideLoading()
            })
    } else if (arg === 'undoAudit') {
        console.log(111)
        _this.clientPop('info', _this.undoAudit, ()=>{
            showLoading()
            auditRequest.undoAudit(_this.auditParams).then(() => {
                hideLoading()
                _this.clientPop('suc', '撤回成功', _this.handleClose)
            }).finally(() => {
                hideLoading()
            })
        })
    } else if (arg === 'submit') {
        _this.saveAll()   //保存
    } else if (arg === 'submitCommit') {
        _this.submitCommit()  //保存并提交
    } else if (arg === 'nullify') {
        _this.setAuditParams(_this.nullifyParams)
        // 客户端弹窗弹出本地页面
        openAppClient('/nullifyDialog', '单据作废原因', () => {
            const auditParams = JSON.parse(localStorage.vuex).auditParams
            showLoading()
            auditRequest.nullify(auditParams).then(() => {
                hideLoading()
                _this.clientPop('suc', '作废成功', _this.handleClose)
            }).finally(() => {
                hideLoading()
            })
        }, null, null, null, 'small')
    }else if (arg === 'deleteData') {
        _this.clickDel()
    }else if (arg === 'print') {
        const data = await printData()
        webprintReport(data)
    }

}
//保存全部数据
function saveAll (vueObject, requestFn) {
    const _this = vueObject
    showLoading()
    _this.errorList = []
    Promise.all(requestFn())
        .then(() => {
            console.log('then')
            hideLoading()
            _this.clientPop('suc', '保存成功')
        })
        .catch(err => {
            console.log(err, 'err')
            let errMsg = null
            if(  typeof err === 'string') {
                errMsg = err
            }else if(err instanceof Array) {
                errMsg = err.join('，')
            }else if(err instanceof Object) {
                if(err.code) {
                    errMsg = Object.values(err.data)
                }else{
                    errMsg = err
                }
            }
            _this.clientPop('err', `保存失败${errMsg !== null ? '\n错误信息：' +  errMsg : ''}
                    `, ()=>{
                _this.scorllError()
            })
        })
        .finally(() => {
            console.log('finally')
            hideLoading()
        })
}
//保存并提交
function submitCommit (vueObject, requestFn) {
    const _this = vueObject

    // if (_this.detailedTableData.length === 0) {
    //     _this.errorMsg = []
    //     let str = '计划明细不能空！'
    //     _this.errorMsg.push(str)
    //     _this.setError('detailed')
    //     _this.scorllError()
    //     return
    // }
    showLoading()
    _this.errorList = []
    Promise.all(requestFn())
        .then(() => {
            auditRequest.commit(_this.auditParams).then(()=>{
                hideLoading()
                _this.clientPop('suc', '提交成功', _this.handleClose)
            })
        })
        .catch(err => {
            let errMsg = null
            if(  typeof err === 'string') {
                errMsg = err
            }else if(err instanceof Array) {
                errMsg = err.join('，')
            }else if(err instanceof Object) {
                if(err.code) {
                    errMsg = Object.values(err.data)
                }else{
                    errMsg = err
                }
            }
            _this.clientPop('err', `提交失败${errMsg !== null ? '\n错误信息：' +  errMsg : ''}
                    `, ()=>{
                _this.scorllError()
            })
        })
        .finally(() => {
            hideLoading()
        })
}

// 原单明细删除明细逻辑处理
/***
 * row:当前行数据
 * $index 当前处于第几行
 * _this 源组件的vue实例
 * basicFormReset 当明细数据为空 或者changeType全部为-1的时候需要清空的基本信息的字段
 */
function deleteLogic (row, $index, _this, basicFormReset = []) {
    if (row.dtlId) {
        _this.$set(_this.detailedTableData[0].children[$index - 1], 'changeType', -1)
    } else {
        _this.$set( _this.detailedTableData[0].children.splice($index - 1, 1))
    }

    if (_this.detailedTableData[0].children) {
        const newArr = _this.detailedTableData[0].children.filter(v => v.changeType !== -1)

        if (newArr.length === 0) {

            // 数据清零
            basicFormReset.forEach(item =>_this.basicForm[item] = 0)
            _this.errorMsg = []
        } else {
            _this.collectCount && _this.collectCount()
            _this.onTaxRate && _this.onTaxRate()

        }

    }

}

// 用户判断当前明细列表展示数据
function detailedTableDataComputed (detailedTableData) {
    if (!fn.checkEmpty(detailedTableData)) {
        const newArr = detailedTableData[0].children.filter(v => v.changeType !== -1)
        if (newArr.length === 0) {
            return []
        }
        return detailedTableData
    } else {
        return []
    }
}
export {
    exas,
    saveAll,
    submitCommit,
    deleteLogic,
    detailedTableDataComputed
}